package com.neborosoft.android.gui.wrappers;

import android.os.Parcelable;
import android.widget.AbsListView;
import com.neborosoft.FlyingDog.android.MyActivity;
import com.neborosoft.android.gui.Gui;
import com.neborosoft.android.gui.adapters.listview.ViewArrayAdapter;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: CM
 * Date: 08.11.12
 * Time: 1:42
 * To change this template use File | Settings | File Templates.
 */
public class ListViewStateSaver {
    private HashMap<AbsListView, HashMap<Object,Parcelable> > listStates =
            new HashMap<AbsListView, HashMap<Object, Parcelable>>();
    private HashMap<Object, Parcelable> currentListStates = new HashMap<Object, Parcelable>();

    public void setListView(AbsListView listView){
        if(currentListView == listView){
            return;
        }

        saveCurrentListViewState();

        currentListStates = listStates.get(listView);
        if(currentListStates == null){
            currentListStates = new HashMap<Object, Parcelable>();
            listStates.put(listView, currentListStates);
        }

        currentListView = listView;
        this.key = null;
        Gui.setAdapter(currentListView,null);
        //currentListView.setAdapter(null);
    }

    private AbsListView currentListView;
    private Object key;

    public ListViewStateSaver() {

    }

    public ViewArrayAdapter getAdapter(){
        if(currentListView != null) {
            return (ViewArrayAdapter)currentListView.getAdapter();
        } else {
            return null;
        }
    }

    public AbsListView getListView() {
        return currentListView;
    }

    private void saveCurrentListViewState(){
        if(this.key != null){
            Parcelable state = currentListView.onSaveInstanceState();
            currentListStates.put(this.key, state);
        }
    }

    public void setAdapter(ViewArrayAdapter adapter, Object key){
        if(adapter == null || key == null){
            throw new NullPointerException();
        }

        saveCurrentListViewState();
        Gui.setAdapter(currentListView, adapter);
        //currentListView.setAdapter(adapter);

        Parcelable state = currentListStates.get(key);
        if(state != null){
            currentListView.onRestoreInstanceState(state);
        }

        this.key = key;
    }
}
